package com.lbd.statistics.service.impl;

import com.lbd.base.service.BaseServiceImpl;

import com.lbd.statistics.controller.vo.PlatformStatisticsVo;
import com.lbd.statistics.service.PlatformStatisticsService;
import org.apache.log4j.Logger;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by sun on 2016/12/1.
 */
@Service
public class PlatformStatisticsServiceImpl implements PlatformStatisticsService {
    private final Logger log = Logger.getLogger(this.getClass());

    @Autowired
    public EntityManager em;

    @Override
    public PlatformStatisticsVo findByTime(PlatformStatisticsVo platformStatictisVo) {
        Map<String, Object> parameter = new HashMap<String, Object>();
        PlatformStatisticsVo vo = new PlatformStatisticsVo();
        HashMap<String, Object> map = new HashMap<String, Object>();
        StringBuffer sqlStr = new StringBuffer();
        if (platformStatictisVo != null) {
            if (platformStatictisVo.getStartDate() != null && platformStatictisVo.getStartDate().toString().length() > 0) {
                sqlStr.append(" and created_date >= :startDate");
                parameter.put("startDate", platformStatictisVo.getStartDate());

            }
            if (platformStatictisVo.getEndDate() != null && platformStatictisVo.getEndDate().toString().length() > 0) {
                sqlStr.append(" and created_date <= :endDate");
                parameter.put("endDate", platformStatictisVo.getEndDate());
            }
        }
        StringBuffer sql = new StringBuffer();
        /**
         * 查询交易总额、交易总笔数
         */
        try {
            sql.append("select COUNT(1) as trade_num,SUM(htje) as trade_amount from target_info");
            sql.append(" where target_state in(4,5) ");
            sql.append(sqlStr);
            map = (HashMap<String, Object>) findMapByPageNativeQuery(parameter, sql.toString());
            vo.setTradeNum(map == null || map.get("trade_num") == null ? 0 : Integer.valueOf(map.get("trade_num").toString()));
            vo.setTradeAmount(map == null || map.get("trade_amount") == null ? BigDecimal.ZERO : BigDecimal.valueOf((double) map.get("trade_amount")));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询交易总额、交易总笔数失败,e=" + e.getMessage());
        }

        /**
         * 查询总用户数
         */
        try {
            sql = new StringBuffer();
            sql.append("SELECT COUNT(1) as user_num FROM user");
            sql.append(" where 1=1 ");
            sql.append(sqlStr);
            map = (HashMap<String, Object>) findMapByPageNativeQuery(parameter, sql.toString());
            vo.setUserNum(map == null || map.get("user_num") == null ? 0 : Integer.valueOf(map.get("user_num").toString()));
        } catch (Exception e) {
            log.error("查询总用户数失败");
        }
        /**
         * 查询总充值用户数、总充值额
         */
        try {
            sql = new StringBuffer();
            sql.append("SELECT COUNT(DISTINCT user_id) as recharge_num,sum(actual_amount) as recharge_amount FROM trading_record");
            sql.append(" where type=1 and state=2 ");
            sql.append(sqlStr);
            map = (HashMap<String, Object>) findMapByPageNativeQuery(parameter, sql.toString());
            vo.setRechargeNum(map == null || map.get("recharge_num") == null ? 0 : Integer.valueOf(map.get("recharge_num").toString()));
            vo.setRechargeAmount(map == null || map.get("recharge_amount") == null ? BigDecimal.ZERO : BigDecimal.valueOf((double) map.get("recharge_amount")));
        } catch (Exception e) {
            log.error("查询总充值用户数、总充值额失败");
        }

        /**
         * 查询总提现用户数、总提现额、总提现手续费
         */
        try {
            sql = new StringBuffer();
            sql.append("SELECT COUNT(DISTINCT user_id) as withdraw_num,sum(actual_amount) as withdraw_amount,sum(service_charge) as fee FROM trading_record");
            sql.append(" where type=2 and state=2 ");
            sql.append(sqlStr);
            map = (HashMap<String, Object>) findMapByPageNativeQuery(parameter, sql.toString());
            vo.setWithdrawNum(map == null || map.get("withdraw_num") == null ? 0 : Integer.valueOf(map.get("withdraw_num").toString()));
            vo.setWithdrawAmount(map == null || map.get("withdraw_amount") == null ? BigDecimal.ZERO : BigDecimal.valueOf((double) map.get("withdraw_amount")));
            vo.setWithdrawFee(map == null || map.get("fee") == null ? BigDecimal.ZERO : BigDecimal.valueOf((double) map.get("fee")));
        } catch (Exception e) {
            log.error("查询总提现用户数、总提现额、总提现手续费失败");
        }

        /**
         * 查询总平台手续费
         */
        try {
            sql = new StringBuffer();
            sql.append("SELECT sum(fwf) as service_fee from target_info ");
            sql.append(" where target_state in(4,5)");
            sql.append(sqlStr);
            map = (HashMap<String, Object>) findMapByPageNativeQuery(parameter, sql.toString());
            vo.setServiceFee(map == null || map.get("service_fee") == null ? BigDecimal.ZERO : BigDecimal.valueOf((double) map.get("service_fee")));
        } catch (Exception e) {
            log.error("查询总平台手续费失败");
        }


        /**
         * 查询总垫付手续费
         */
        vo.setCommission(BigDecimal.ZERO);

        vo.setStartDate(platformStatictisVo.getStartDate());
        vo.setEndDate(platformStatictisVo.getEndDate());

        return vo;
    }

    /**
     * nativesql返回Map
     *
     * @param parameter nativeSql 的参数
     * @param nativeSql nativeSql 字符串
     * @return
     */
    public Map findMapByPageNativeQuery(Map<String, Object> parameter, String nativeSql) {
        Query nativeQuery = em.createNativeQuery(nativeSql);
        nativeQuery.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
        for (String key : parameter.keySet()) {
            nativeQuery.setParameter(key, parameter.get(key));
        }
        return (Map) nativeQuery.getSingleResult();
    }
}
